package cn.lili.modules.member.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.PayWayEnum;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.mapper.VipConfigMapper;
import cn.lili.modules.member.service.VipConfigService;
import cn.lili.modules.system.entity.dos.LiVipConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author asus
* @description 针对表【li_vip_config(会员配置表)】的数据库操作Service实现
* @createDate 2023-11-07 13:52:33
*/
@Service
public class VipConfigServiceImpl extends ServiceImpl<VipConfigMapper, LiVipConfig>
    implements VipConfigService{
    public Integer total=7;
    @Autowired
    private VipConfigMapper configMapper;
    /**
     * 会员配置更新
     * @param liVipConfig
     * @return
     */
    @Override
    public ResultMessage<Object> configUpdate(LiVipConfig liVipConfig) {
        return getUpdateResult(liVipConfig);

    }

    /**
     * 会员支付方式修改
     * @param payWay
     * @param id
     * @return
     */
    @Override
    public ResultMessage<Object> updatePayWay(String payWay,String id) {
        /**
         * 1.空值判断
         * 2.支付方式判断
         */
        if ((StringUtils.isEmpty(payWay))||(StringUtils.isEmpty(id)))
            throw new ServiceException(ResultCode.PARAMS_ERROR);

        checkPayWay(payWay);

        UpdateWrapper<LiVipConfig> wrapper=new UpdateWrapper<>();
        wrapper.eq("id", id)
                .set("pay_way", payWay);
        return this.update(wrapper)?ResultUtil.success():ResultUtil.error();
    }

    /**
     * 添加会员配置
     * @param vipConfig
     * @return
     */
    @Override
    public ResultMessage<Object> saveConfig(LiVipConfig vipConfig) {
        return getAddResult(vipConfig);
    }

    @Override
    public ResultMessage<Object> getList() {
        LambdaQueryWrapper<LiVipConfig>wrapper=new LambdaQueryWrapper<>();
        wrapper.orderByDesc(LiVipConfig::getCreateTime);
        return ResultUtil.data(this.page(new Page<>(1,99),wrapper));
    }

    private ResultMessage<Object> getAddResult(LiVipConfig vipConfig) {
        /**
         * 1.空值判断
         * 2.支付方式判断
         */
        if (Objects.isNull(vipConfig))
            throw new ServiceException(ResultCode.PARAMS_ERROR);

        if ((Objects.isNull(vipConfig.getDefaultTime()))||
                (Objects.isNull(vipConfig.getVipCount()))||
                (Objects.isNull(vipConfig.getVipPrice()))||
                (Objects.isNull(vipConfig.getVipName()))||
                (Objects.isNull(vipConfig.getPayWay())))
            throw new ServiceException(ResultCode.PARAMS_ERROR);

        checkPayWay(vipConfig.getPayWay());

        vipConfig.setId(SnowFlake.getIdStr());
        vipConfig.setCreateBy(UserContext.getCurrentId());
        vipConfig.setCreateTime(Date.from(Instant.now()));

        if (vipConfig.getIsDefault()==1) {
            UpdateWrapper<LiVipConfig> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("is_default", 0);
            this.update(updateWrapper);
        }

        return this.save(vipConfig)?ResultUtil.success():ResultUtil.error();
    }


    private void checkPayWay(String payWay) {

        //将传过来的payway切割，然后循环遍历支付方式枚举对比
        String[] ways = payWay.split(",");
        //判断支付方式是否有设置平台添加方式
        for (int i = 0; i < ways.length; i++) {
            if (ways[i].equals(PayWayEnum.MANAGE_ADD.getValue()+"")) {
                throw new ServiceException(ResultCode.PAY_WAY_ERROR);
            }
        }
        //判断支付方式是否正确
        for (int i = 0; i < ways.length; i++) {
            int n=0;
            for (PayWayEnum pay:PayWayEnum.values()){
                boolean result = ways[i].equals(pay.getValue()+"");
                if (result)
                    break;
                else
                    n++;
            }
            if (n>=total)
                throw new ServiceException(ResultCode.PAY_WAY_ERROR);
        }
    }


    private ResultMessage<Object> getUpdateResult(LiVipConfig liVipConfig) {
        if (Objects.isNull(liVipConfig))
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        try{
            UpdateWrapper<LiVipConfig>wrapper=new UpdateWrapper<>();

            if (!StringUtils.isEmpty(liVipConfig.getPayWay()))
                checkPayWay(liVipConfig.getPayWay());

            liVipConfig.setUpdateBy(UserContext.getCurrentId());
            liVipConfig.setUpdateTime(Date.from(Instant.now()));

            wrapper.eq("id", liVipConfig.getId())
                    .set(Objects.nonNull(liVipConfig.getPayWay()),"pay_way", liVipConfig.getPayWay())
                    .set(Objects.nonNull(liVipConfig.getVipCount()),"vip_count", liVipConfig.getVipCount())
                    .set(Objects.nonNull(liVipConfig.getVipName()),"vip_name", liVipConfig.getVipName())
                    .set(Objects.nonNull(liVipConfig.getVipPrice()),"vip_price", liVipConfig.getVipPrice())
                    .set(Objects.nonNull(liVipConfig.getVipDetail()),"vip_detail", liVipConfig.getVipDetail())
                    .set(Objects.nonNull(liVipConfig.getDefaultTime()),"default_time", liVipConfig.getDefaultTime())
                    .set(Objects.nonNull(liVipConfig.getIsDefault()),"is_default",liVipConfig.getIsDefault())
                    .set("update_by", liVipConfig.getUpdateBy())
                    .set("update_time", liVipConfig.getUpdateTime());

            if (liVipConfig.getIsDefault()==1){
                UpdateWrapper<LiVipConfig>updateWrapper=new UpdateWrapper<>();
                updateWrapper.set("is_default",0);
                this.update(updateWrapper);
                return this.update(wrapper)?ResultUtil.success():ResultUtil.error();
            }
            if (liVipConfig.getIsDefault()==0){
                //改为非默认时，查所有配置，将查询节果遍历，如果没有默认，则return.error
                List<LiVipConfig>list=configMapper.getAll();
                for (int i = 0; i < list.size(); i++) {
                    if ((list.get(i).getIsDefault()==1)&&!Objects.equals((list.get(i).getId()),liVipConfig.getId())){
                        return this.update(wrapper)?ResultUtil.success():ResultUtil.error();
                    }
                }
            }
            return ResultUtil.error(400,"必须保证有一个默认配置");
        }catch (ServiceException e){
        return ResultUtil.error(400,e.getMsg());
        }
    }
    @Override
    public LiVipConfig getByDefault() {
        LambdaQueryWrapper<LiVipConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LiVipConfig::getIsDefault, 1);
        queryWrapper.last("limit 1");
        return this.baseMapper.selectOne(queryWrapper);
    }
}




